<?php

/**
 * @CreateTime:   2020/8/19 12:30 上午
 * @Author:       huizhang  <2788828128@qq.com>
 * @Copyright:    copyright(2020) Easyswoole all rights reserved
 * @Description:  用户控制器
 */

namespace App\Api;


use Common\ApiController;
use Common\Services\JwtService;
use Common\Services\MemberService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class UserController extends ApiController
{

    public array $signOptional = ['register', 'login'];

    public function register(): array
    {
        $request = $this->request;

        $username = $request->input('username');
        $password = $request->input('password');
        $mobile = $request->input('mobile');
        $smsCode = $request->input('smsCode');

        if (empty($username)) {
            return $this->writeJson(400, null, 'username 不能为空');
        }

        if (empty($password)) {
            return $this->writeJson(400, null, 'password 不能为空');
        }

        $res = MemberService::register($username, $password, '', $mobile, $smsCode);
        if ($res['code']) {
            return $this->writeJson(200, $res['data'], $res['message']);
        } else {
            return $this->writeJson(400, $res['data'], $res['message']);
        }
    }

    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function login(): array
    {
        $request = $this->request;
        $username = $request->input('username');
        $password = $request->input('password');

        if (empty($username)) {
            return $this->writeJson(400, null, 'username 不能为空');
        }

        if (empty($password)) {
            return $this->writeJson(400, null, 'password 不能为空');
        }
        $project_id = $this->getAttribute('project_id');
        $res = JwtService::createToken($username, $password,$project_id);
        return $this->writeJson(200, $res, '登录成功');
    }

    /**
     * 用户信息.
     *
     * @return array
     *                CreateTime: 2020/8/19 12:37 上午
     */
    public function userInfo(): array
    {
        // 获取 get 参数
        $name = $this->request->input('name');

        // 输出到终端
        var_dump($name);

        // 返回给客户端
        $this->response->write($name . PHP_EOL);
        return $this->writeJson(200,[]);
    }

    /**
     * 接口请求量.
     *
     * CreateTime: 2020/8/19 12:37 上午
     */
    public function requestTotal(): array
    {
        $this->response->write('请求数+1' . PHP_EOL);
        return $this->writeJson(200,[]);

        // 还可以 return，但不要两个方法互相调用，会导致死循环
    }


}
